package cn.smxy.admin.service.impl;

import cn.smxy.admin.param.PlantPageAdminParam;
import cn.smxy.admin.service.PlantService;
import cn.smxy.client.CategoryClient;
import cn.smxy.client.PlantClient;
import cn.smxy.param.FamilyIdsParam;
import cn.smxy.param.PlantAddParam;
import cn.smxy.param.PlantPageParam;
import cn.smxy.param.PlantRemoveParam;
import cn.smxy.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PlantServiceImpl implements PlantService {

    @Autowired
    private PlantClient plantClient;
    @Autowired
    private CategoryClient categoryClient;

    /**
     * 删除植物作品
     *
     * @param plantRemoveParam
     * @return
     */
    @Override
    public R remove(PlantRemoveParam plantRemoveParam) {
        plantRemoveParam.setUserId(0L); // 管理员删除，默认用户ID为0
        return plantClient.remove(plantRemoveParam);
    }

    /**
     * 修改植物作品信息
     *
     * @param plantAddParam
     * @return
     */
    @Override
    public R update(PlantAddParam plantAddParam) {
        // 因科属名为同一字段，所以如果属名ID不为null，将科属名置为属名ID
        Long genusId = plantAddParam.getGenusId();
        if(genusId != null) {
            plantAddParam.setFamilyId(genusId);
        }
        return plantClient.update(plantAddParam);
    }

    /**
     * 上传植物作品
     *
     * @param plantAddParam
     * @return
     */
    @Override
    public R add(PlantAddParam plantAddParam) {
        // 因科属名为同一字段，所以如果属名ID不为null，将科属名置为属名ID
        Long genusId = plantAddParam.getGenusId();
        if(genusId != null) {
            plantAddParam.setFamilyId(genusId);
        }
        // 管理员添加植物作品时用户ID为0
        plantAddParam.setUserId(0L);
        return plantClient.add(plantAddParam);
    }

    /**
     * 单种群多科属分页展示接口
     *
     * @param plantPageAdminParam 分页参数
     * @return
     */
    @Override
    public R page(PlantPageAdminParam plantPageAdminParam) {
        PlantPageParam plantPageParam = new PlantPageParam();
        if(plantPageAdminParam.getFamilyId() != null) {
            // 查询该科属下的所有子集
            List<Long> ids = new ArrayList<>();
            ids.add(plantPageAdminParam.getFamilyId());
            FamilyIdsParam familyIdsParam = new FamilyIdsParam(ids);
            List<Long> familyIds = categoryClient.list(familyIdsParam);
            // 重新封装单种群多科属分页参数
            plantPageParam.setFamilyIds(familyIds);
        }
        plantPageParam.setCurrentPage(plantPageAdminParam.getCurrentPage());
        plantPageParam.setPageSize(plantPageAdminParam.getPageSize());
        plantPageParam.setCategoryId(plantPageAdminParam.getCategoryId());
        plantPageParam.setFuzzyName(plantPageAdminParam.getFuzzyName());
        return plantClient.page(plantPageParam);
    }
}
